package com.alks.function.service.impl.packImpl;

import com.alibaba.fastjson2.JSON;
import com.alks.common.aop.AutoPageAop;
import com.alks.common.aop.RedisLock;
import com.alks.common.data.dto.SysUserTokenDTO;
import com.alks.common.data.thread.UserIdThread;
import com.alks.common.service.RedisService;
import com.alks.common.utils.DateUtils;
import com.alks.common.utils.excelUtils.ExcelPoiUtils;
import com.alks.common.utils.excelUtils.ExcelUtils;
import com.alks.common.utils.stringUtils.ZStringUtils;
import com.alks.entity.data.entity.*;
import com.alks.entity.data.enums.ResultCodeEnum;
import com.alks.entity.data.response.ResponseInfo;
import com.alks.entity.exception.ServiceErrorException;
import com.alks.function.data.request.PcSoleInStockReq;
import com.alks.function.data.request.order.PcOrderDataRsjRequest;
import com.alks.function.data.request.pack.*;
import com.alks.function.mapper.PcOrderHeadMapping;
import com.alks.function.mapper.ProdDynamicHeadMapper;
import com.alks.function.mapper.pack.PackMaterialMapping;
import com.alks.function.service.pack.PackMaterialService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.*;

/**
 * @author:xxxxx
 * @create: 2023-08-01 14:47
 * @Description: 包材查询
 */
@Service
@Slf4j
public class PackMaterialServiceImpl implements PackMaterialService {

    @Autowired
    PackMaterialMapping packMaterialMapping;

    @Override
    public ResponseInfo listPcPackMaterialInStorage(PcPackMaterialRequest request) {
        if (request == null) {
            return ResponseInfo.error(ResultCodeEnum.LOGIN_CONFIG_IS_NULL.getMessage(), ResultCodeEnum.LOGIN_CONFIG_IS_NULL.getCode());
        }
        if (request.getPageNum() == null || request.getPageSize() == null) {
            request.setPageNum(1);
            request.setPageSize(10);
        }
        PageHelper.startPage(request.getPageNum(), request.getPageSize(), false);
        HashMap<String, Object> map = new HashMap<>();
        List<PackMaterialStorageRep> reqs = packMaterialMapping.listPackMaterialStorage(request);
        Long total = packMaterialMapping.getPackInStorageTotal(request);
        Long qtyTotal = packMaterialMapping.getPackInStorageQtyTotal(request);
        map.put("list", reqs);
        map.put("total", total);
        map.put("qtyTotal", qtyTotal);
        return ResponseInfo.ok(map);
    }

    @Autowired
    RedisService redisService;

    @Override
    public ResponseInfo getPcPackMaterialInStorageCondition() {
        String key = "getPcPackMaterialInStorageCondition";
        Set set = redisService.scan(key);
        if (set.size() > 0) {
            PcPackMaterialInStorageCondition material = JSON.parseObject(redisService.get(key), PcPackMaterialInStorageCondition.class);
            return ResponseInfo.ok(material);
        }
        PcPackMaterialInStorageCondition material = new PcPackMaterialInStorageCondition();
        List<String> slipReason = packMaterialMapping.getPackSlipReasonInStorage();
        List<Map<String, String>> dept = packMaterialMapping.getPackDeptInStorage();
        List<Map<String, String>> vendor = packMaterialMapping.getPackVenDorInStorage();
        List<String> types = packMaterialMapping.getPackTypeInStorage();
        material.setDept(dept);
        material.setTypes(types);
        material.setSlipReason(slipReason);
        material.setVendor(vendor);
        redisService.set(key, JSON.toJSONString(material));
        return ResponseInfo.ok(material);
    }

    @Override
    public ResponseInfo getPcPackMaterialOutCondition() {
        PcPackMaterialOutCondition condition = new PcPackMaterialOutCondition();
        List<Map<String, String>> dept = packMaterialMapping.getPcPackMaterialOutDept();
        List<String> slipReason = packMaterialMapping.getPcPackMaterialOutSlipReason();
        condition.setDept(dept);
        condition.setSlipReason(slipReason);
        return ResponseInfo.ok(condition);
    }

    @Override
    public ResponseInfo getPackMaterialOut(PcPackMaterialOutRequest request) {
        if (request == null) {
            return ResponseInfo.error(ResultCodeEnum.LOGIN_CONFIG_IS_NULL.getMessage(), ResultCodeEnum.LOGIN_CONFIG_IS_NULL.getCode());
        }
        if (request.getPageNum() == null || request.getPageSize() == null) {
            request.setPageNum(1);
            request.setPageSize(10);
        }
        PageHelper.startPage(request.getPageNum(), request.getPageSize(), false);
        Map<String, Object> map = new HashMap<>();
        List<PcPackMaterialOutRep> list = packMaterialMapping.getPackMaterialOut(request);
        Integer total = packMaterialMapping.getPackMaterialOutTotal(request);
        BigDecimal qtySum = packMaterialMapping.getPackMaterialOutQtySum(request);
        map.put("list", list);
        map.put("total", total);
        map.put("qtySum", qtySum);
        return ResponseInfo.ok(map);
    }

    @Override
    public ResponseInfo getPcPackStockCondition() {
        List<PcPackMaterialStockCondition> list = packMaterialMapping.getPcPackStockCondition();
        return ResponseInfo.ok(list);
    }

    @Override
    public ResponseInfo getPcPackStock(PcPackStockRequest request) {
        if (request == null) {
            return ResponseInfo.error(ResultCodeEnum.LOGIN_CONFIG_IS_NULL.getMessage(), ResultCodeEnum.LOGIN_CONFIG_IS_NULL.getCode());
        }
        if (request.getPageNum() == null || request.getPageSize() == null) {
            request.setPageNum(1);
            request.setPageSize(10);
        }
        PageHelper.startPage(request.getPageNum(), request.getPageSize(), false);
        HashMap<String, Object> map = new HashMap<>();
        List<PcPackStockRep> list = packMaterialMapping.getPcPackStock(request);
        Long total = packMaterialMapping.getPcPackStockTotals(request);
        map.put("list", list);
        map.put("total", total);
        return ResponseInfo.ok(map);
    }

    @Override
    public ResponseInfo getPcPackStockInOut(String mtlNo, String mtlName) {
        HashMap<String, Object> inMap = new HashMap<>();
        HashMap<String, Object> outMap = new HashMap<>();
        HashMap<String, Object> map = new HashMap<>();
        List<PcPackInDetailRep> in = packMaterialMapping.getPcPackStockIn(mtlNo, mtlName);
        List<PcPackOutDetailRep> out = packMaterialMapping.getPcPackStockOut(mtlNo, mtlName);
        Long inTotal = packMaterialMapping.getPcPackStockInTotal(mtlNo, mtlName);
        Long outTotal = packMaterialMapping.getPcPackStockOutTotal(mtlNo, mtlName);
        inMap.put("total", inTotal);
        outMap.put("total", outTotal);
        inMap.put("list", in);
        outMap.put("list", out);
        map.put("in", inMap);
        map.put("out", outMap);
        return ResponseInfo.ok(map);
    }

    @Override
    public ResponseInfo getPcPackFaceCondition(String levelCode1, String levelCode2) {
        Map<String, Object> map = new HashMap<>();
        List<PcPackFaceMtlConditionRep> list = null;
        if (levelCode1 != null && !"".equals(levelCode1)) {
            if (levelCode2 != null && !"".equals(levelCode2)) {
                list = packMaterialMapping.getPcPackFaceCondition2(levelCode2);
                map.put("classifies", list);
                return ResponseInfo.ok(map);
            }
            list = packMaterialMapping.getPcPackFaceCondition2(levelCode1);
            map.put("classifies", list);
            return ResponseInfo.ok(map);
        }
        list = packMaterialMapping.getPcPackFaceCondition1();
        map.put("classifies", list);
        return ResponseInfo.ok(map);
    }

    @Override
    public ResponseInfo getPcPackFaceMtl(PcPackFaceMtlRequest request) {
        Map<String, Object> map = new HashMap<>();
        List<PcPackFaceMtlRep> list = packMaterialMapping.getPcPackFaceMtl(request);
        map.put("list", list);
        return ResponseInfo.ok(map);
    }

    @Override
    public ResponseInfo getPcPackFaceMtlDeTail(PcPackFaceMtlDetailRequest request) {
        Map<String, Object> map = new HashMap<>();
        List<PcPackFaceMtlDetailRep> list = packMaterialMapping.getPcPackFaceMtlDeTail(request);
        map.put("list", list);
        return ResponseInfo.ok(map);
    }

    @Override
    @AutoPageAop
    public ResponseInfo collectAllList(PcOrderDataRsjRequest request, String flag) {
        if ("1".equals(flag)) {
            request.setProdUserName(UserIdThread.get().getUserName());
        }
        Map<String, Object> map = new HashMap<>();
        List<String> typeList = Arrays.asList("16", "17");
        if (typeList.contains(request.getChoose())) {
            List<PcCutStitchRep> lists = packMaterialMapping.collectCutD1(request);
            Page<PcCutStitchRep> pages = (Page<PcCutStitchRep>) lists;
            map.put("list", lists);
            map.put("total", pages.getTotal());
            return ResponseInfo.ok(map);
        }
        List<PcDesignGetRep> list = packMaterialMapping.collectAllList(request);
        Page<PcDesignGetRep> page = (Page<PcDesignGetRep>) list;
        //裁断和针车的试板/大货
        map.put("list", list);
        map.put("total", page.getTotal());
        List<String> strings = Arrays.asList("1", "2");
        if (strings.contains(request.getChoose())) {
            BigDecimal orderTotal = packMaterialMapping.collectAllOrderQty(request);
            map.put("orderTotal", orderTotal);
        }
        if (Arrays.asList("3", "8", "9", "10", "11", "12").contains(request.getChoose())) {
            BigDecimal prodTotal = packMaterialMapping.collectAllProdQty(request);
            map.put("prodTotal", prodTotal);
        }
        return ResponseInfo.ok(map);
    }

    @Autowired
    ProdDynamicHeadMapper prodDynamicHeadMapper;

    @Override
    public ResponseInfo deleteFromProdStatus(List<PcDesignGetRep> rep, String choose) {
        Integer num = packMaterialMapping.deleteFromProdStatus(rep, choose);
        List<String> list = new ArrayList<>();
        if ("12".equals(choose)) {
            //将订单重新写入进度表中
            Integer stdQty = prodDynamicHeadMapper.getStdQty(UserIdThread.get().getCompanyId());
            for (PcDesignGetRep pcDesignGetRep : rep) {
                list.add(pcDesignGetRep.getLotNo());
                //将PC_SCHEDULE_LOT 设置SCH_FLAG为null
            }
            prodDynamicHeadMapper.updateLotOver(list);

        }
        if (num <= 0) {
            return ResponseInfo.error("删除失败");
        }
        return ResponseInfo.ok("删除成功");
    }

    @Override
    public ResponseInfo deleteByCutAStitch(PcCutStitchRep rep, String choose) {
        packMaterialMapping.deleteByCutAStitch(rep, choose);
        return ResponseInfo.ok("删除成功");
    }

    @Override
    public void downloadPcPackIn(HttpServletResponse response, PcPackMaterialRequest request) throws UnsupportedEncodingException {
        Map<String, Object> map = new HashMap<>();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        List<PackMaterialStorageRep> reqs = packMaterialMapping.listPackMaterialStorage(request);
        reqs.forEach(x -> x.setDate(format.format(x.getSlipDate())));
        map.put("list", reqs);
        ExcelPoiUtils.writeExcelList(response, map, "templates/包材入库模板.xlsx");
    }

    @Override
    public void downloadPackOut(HttpServletResponse response, PcPackMaterialOutRequest request) throws UnsupportedEncodingException {
        Map<String, Object> map = new HashMap<>();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        List<PcPackMaterialOutRep> list = packMaterialMapping.getPackMaterialOut(request);
        list.forEach(x -> {
            x.setDate(format.format(x.getSlipDate()));
        });
        map.put("list", list);
        ExcelPoiUtils.writeExcelList(response, map, "templates/包材出库模板.xls");
    }

    @Override
    public void downloadPcPackMtl(HttpServletResponse response, PcPackFaceMtlDetailRequest request) throws IOException {
        List<PcPackFaceMtlDetailRep> list = packMaterialMapping.getPcPackFaceMtlDeTail(request);
        ExcelUtils.creatByTemplate(response, "面材材料导出.xls", DateUtils.dateTimeNow(), list);
    }

    @Autowired
    PcOrderHeadMapping pcOrderHeadMapping;

    @Override
    @Transactional
    public ResponseInfo scanCollectAll(ScanCollectionAllReq req, String choose) {
        if(ZStringUtils.isNotEmpty(req.getLotNo())) req.setLotNo(req.getLotNo().trim());
        String dispatchNo = req.getDispatchNo();
        if (ZStringUtils.isNotEmpty(dispatchNo)) req.setDispatchNo(dispatchNo.trim());
        if ("".equals(req.getLotNo()) || req.getLotNo() == null) {
            if (ZStringUtils.isEmpty(dispatchNo)) return ResponseInfo.error("指令不能为空");
        }
        //查看该指令是否在pc_order_head
        String no = req.getLotNo();
        Integer count = packMaterialMapping.getCountByLotNo(no);
        if (count <= 0) {
            if (ZStringUtils.isEmpty(dispatchNo)) return ResponseInfo.error("指令不存在");
        }
        List<String> noList = Arrays.asList(no);
        List<PcOrderStyleColorDdDetailRep> reps = pcOrderHeadMapping.pcOrderStyleColorDdDetail(noList);
        PcOrderStyleColorDdDetailRep rep = ZStringUtils.isEmpty(reps) ? null : reps.get(0);
        String prodStep = "";
        List<String> list;
        if (req.getStitchBarcode() != null && !req.getStitchBarcode().isEmpty()) {
            String lotNo = packMaterialMapping.getLotNoByStitchBarcode(req, "9");
            req.setLotNo(lotNo);
        }
        List<String> lotNoByProdStep1 = packMaterialMapping.getLotNoByProdStep(req, "1");
        List<String> lotNoByProdStep2 = packMaterialMapping.getLotNoByProdStep(req, "2");
        List<String> lotNoByProdStep3 = packMaterialMapping.getLotNoByProdStep(req, "3");
        List<String> lotNoByProdStep4 = packMaterialMapping.getLotNoByProdStep(req, "4");
        List<String> lotNoByProdStep5 = packMaterialMapping.getLotNoByProdStep(req, "5");
        List<String> lotNoByProdStep6 = packMaterialMapping.getLotNoByProdStep(req, "6");
        List<String> lotNoByProdStep7 = packMaterialMapping.getLotNoByProdStep(req, "7");
        List<String> lotNoByProdStep8 = packMaterialMapping.getLotNoByProdStep(req, "8");
        List<String> lotNoByProdStep9 = packMaterialMapping.getLotNoByProdStep(req, "9");
        List<String> lotNoByProdStep10 = packMaterialMapping.getLotNoByProdStep(req, "10");
        List<String> lotNoByProdStep11 = packMaterialMapping.getLotNoByProdStep(req, "11");
        List<String> lotNoByProdStep12 = packMaterialMapping.getLotNoByProdStep(req, "12");
        List<String> lotNoByProdStep13 = packMaterialMapping.getLotNoByProdStep(req, "13");
        List<String> lotNoByProdStep14 = packMaterialMapping.getLotNoByProdStep(req, "14");
        //获取当前订单的采集数量
        BigDecimal prodQty = packMaterialMapping.getProdQtyByNo(req, choose);
        prodQty = prodQty == null ? new BigDecimal(0) : prodQty;
        //获取订单数量
        BigDecimal currentQty = packMaterialMapping.getCurrentOrderQty(req);
        SysUserTokenDTO user = UserIdThread.get();
        switch (choose) {
            case "1":
                list = packMaterialMapping.getLotNoByProdStep(req, choose);
                if (list != null && !list.isEmpty()) {
                    return ResponseInfo.error("该指令已被采集");
                }
                prodStep = "板房完成";
                packMaterialMapping.insertIntoProdStep(req, prodStep, choose, user);
                return ResponseInfo.ok("采集完成");
            case "2":
                if (lotNoByProdStep1 == null || lotNoByProdStep1.isEmpty()) {
                    return ResponseInfo.error("该指令还没板房采集");
                }
                list = packMaterialMapping.getLotNoByProdStep(req, choose);
                if (list != null && !list.isEmpty()) {
                    return ResponseInfo.error("该指令已被采集");
                }
                prodStep = "备料完成";
                packMaterialMapping.insertIntoProdStep(req, prodStep, choose, user);
                return ResponseInfo.ok("采集完成");

            case "3":
                //判断生产数量是否跟订单数量相同
                prodStep = "裁断完成";
                String strings = redisService.barcodeCreat("C", 4);
                req.setDispatchNo(strings);
                if (req.getWorkId() == null || "".equals(req.getWorkId()) || req.getWorkName() == null || "".equals(req.getWorkName()))
                    return ResponseInfo.error("未扫描员工信息");
                if (lotNoByProdStep1 == null || lotNoByProdStep1.isEmpty()) {
                    return ResponseInfo.error("该指令还没板房采集");
                }
                if (lotNoByProdStep2 == null || lotNoByProdStep2.isEmpty()) {
                    return ResponseInfo.error("该指令还没备料采集");
                }
                if ("补单".equals(req.getProdType())) {
                    packMaterialMapping.insertIntoProdStep(req, prodStep, choose, user);
                    return ResponseInfo.ok("采集完成");
                }
                list = packMaterialMapping.getCutStep(req, choose);
                if (list != null && !list.isEmpty()) {
                    BigDecimal subtract = currentQty.subtract(prodQty);
                    return getInfo(req, choose, currentQty, prodQty, subtract, prodStep, user);
                }
                packMaterialMapping.insertIntoProdStep(req, prodStep, choose, user);
                return ResponseInfo.ok("采集完成");
            case "4":
                prodStep = "电雕完成";
                if (!"Y".equals(rep.getEmbroidFlag())) return ResponseInfo.error("改指令没有设置电雕工艺");
                if ((lotNoByProdStep3 == null || lotNoByProdStep3.isEmpty())) {
                    if (lotNoByProdStep1 == null || lotNoByProdStep1.isEmpty()) {
                        return ResponseInfo.error("该指令还没板房采集");
                    }
                    if (lotNoByProdStep2 == null || lotNoByProdStep2.isEmpty())
                        return ResponseInfo.error("该指令还没备料采集");
                    return ResponseInfo.error("该指令还没裁剪采集");
                }
                list = packMaterialMapping.getLotNoByProdStep(req, choose);
                if (list != null && !list.isEmpty()) {
                    BigDecimal subtract = currentQty.subtract(prodQty);
                    return getInfo(req, choose, currentQty, prodQty, subtract, prodStep, user);
                }
                packMaterialMapping.insertIntoProdStep(req, prodStep, choose, user);
                return ResponseInfo.ok("采集完成");
            case "5":
                if (!"Y".equals(rep.getPrintFlag())) return ResponseInfo.error("改指令没有设置印刷工艺");
                prodStep = "印刷完成";
                if ("Y".equals(rep.getEmbroidFlag())&&(lotNoByProdStep4 == null || lotNoByProdStep4.isEmpty())) {
                    return ResponseInfo.error("该指令还没电雕采集");
                }
                if ((lotNoByProdStep3 == null || lotNoByProdStep3.isEmpty())) {
                    if (lotNoByProdStep1 == null || lotNoByProdStep1.isEmpty()) {
                        return ResponseInfo.error("该指令还没板房采集");
                    }
                    if (lotNoByProdStep2 == null || lotNoByProdStep2.isEmpty())
                        return ResponseInfo.error("该指令还没备料采集");
                    return ResponseInfo.error("该指令还没裁剪采集");
                }
                list = packMaterialMapping.getLotNoByProdStep(req, choose);
                if (list != null && !list.isEmpty()) {
                    BigDecimal subtract = currentQty.subtract(prodQty);
                    if (!currentQty.subtract(prodQty).equals(new BigDecimal(0))) {
                        req.setReplenishmentQty(subtract);
                        packMaterialMapping.insertIntoProdStep(req, prodStep, choose, user);
                        return ResponseInfo.ok("采集完成");
                    } else return ResponseInfo.error("该指令已被采集");
                }
                packMaterialMapping.insertIntoProdStep(req, prodStep, choose, user);
                return ResponseInfo.ok("采集完成");
            case "6":
                if (!"Y".equals(rep.getSewFlag())) return ResponseInfo.error("改指令没有设置无缝工艺");
                prodStep = "无缝完成";
                if ("Y".equals(rep.getPrintFlag())&&(lotNoByProdStep5 == null || lotNoByProdStep5.isEmpty())) {
                    return ResponseInfo.error("该指令还没印刷采集");
                }
                if ((lotNoByProdStep3 == null || lotNoByProdStep3.isEmpty())) {
                    if (lotNoByProdStep1 == null || lotNoByProdStep1.isEmpty()) {
                        return ResponseInfo.error("该指令还没板房采集");
                    }
                    if (lotNoByProdStep2 == null || lotNoByProdStep2.isEmpty())
                        return ResponseInfo.error("该指令还没备料采集");
                    return ResponseInfo.error("该指令还没裁剪采集");
                }
                list = packMaterialMapping.getLotNoByProdStep(req, choose);
                if (list != null && !list.isEmpty()) {
                    BigDecimal subtract = currentQty.subtract(prodQty);
                    return getInfo(req, choose, currentQty, prodQty, subtract, prodStep, user);
                }
                packMaterialMapping.insertIntoProdStep(req, prodStep, choose, user);
                return ResponseInfo.ok("采集完成");
            case "7":
                prodStep = "高频完成";
                if (!"Y".equals(rep.getHfFlag())) return ResponseInfo.error("改指令没有设置高频工艺");
                if ("Y".equals(rep.getPrintFlag())&&(lotNoByProdStep5 == null || lotNoByProdStep5.isEmpty())) {
                    return ResponseInfo.error("该指令还没印刷采集");
                }
                if ((lotNoByProdStep3 == null || lotNoByProdStep3.isEmpty())) {
                    if (lotNoByProdStep1 == null || lotNoByProdStep1.isEmpty()) {
                        return ResponseInfo.error("该指令还没板房采集");
                    }
                    if (lotNoByProdStep2 == null || lotNoByProdStep2.isEmpty())
                        return ResponseInfo.error("该指令还没备料采集");
                    return ResponseInfo.error("该指令还没裁剪采集");
                }
                list = packMaterialMapping.getLotNoByProdStep(req, choose);
                if (list != null && !list.isEmpty()) {
                    BigDecimal subtract = currentQty.subtract(prodQty);
                    return getInfo(req, choose, currentQty, prodQty, subtract, prodStep, user);
                }
                packMaterialMapping.insertIntoProdStep(req, prodStep, choose, user);
                return ResponseInfo.ok("采集完成");
            case "8":
                prodStep = "配套完成";
                if ((lotNoByProdStep6 == null || lotNoByProdStep7 == null || lotNoByProdStep6.isEmpty() || lotNoByProdStep7.isEmpty())) {
                    if ("Y".equals(rep.getHfFlag()) && "Y".equals(rep.getSewFlag()))
                        return ResponseInfo.error("该指令还没高频/无缝采集");
                }
                if ((lotNoByProdStep3 == null || lotNoByProdStep3.isEmpty())) {
                    if (lotNoByProdStep1 == null || lotNoByProdStep1.isEmpty()) {
                        return ResponseInfo.error("该指令还没板房采集");
                    }
                    if (lotNoByProdStep2 == null || lotNoByProdStep2.isEmpty())
                        return ResponseInfo.error("该指令还没备料采集");
                    return ResponseInfo.error("该指令还没裁剪采集");
                }
                list = packMaterialMapping.getCutStep(req, choose);
                if (list != null && !list.isEmpty()) {
                    BigDecimal subtract = currentQty.subtract(prodQty);
                    return getInfo(req, choose, currentQty, prodQty, subtract, prodStep, user);
                }
                packMaterialMapping.insertIntoProdStep(req, prodStep, choose, user);
                return ResponseInfo.ok("采集完成");
            case "9":
                prodStep = "针车派工";
                if (req.getWorkId() == null || "".equals(req.getWorkId()) || req.getWorkName() == null || "".equals(req.getWorkName()))
                    return ResponseInfo.error("未扫描员工信息");
                String string = redisService.barcodeCreat("S", 4);
                req.setStitchBarcode(string);
                if ((lotNoByProdStep8 == null || lotNoByProdStep8.isEmpty())) {
                    return ResponseInfo.error("该指令还没配套采集");
                }
                if ("补单".equals(req.getProdType())) {
                    packMaterialMapping.insertIntoProdStep(req, prodStep, choose, user);
                    return ResponseInfo.ok("采集完成");
                }
                list = packMaterialMapping.getCutStep(req, choose);
                if (list != null && !list.isEmpty()) {
                    BigDecimal subtract = currentQty.subtract(prodQty);
                    return getInfo(req, choose, currentQty, prodQty, subtract, prodStep, user);
                }
                packMaterialMapping.insertIntoProdStep(req, prodStep, choose, user);
                return ResponseInfo.ok("采集完成");
            case "10":
                prodStep = "针车完成";
                if (req.getDispatchNo() == null || req.getDispatchNo().isEmpty()) {
                    return ResponseInfo.error("无此派工单");
                }
                if ((lotNoByProdStep9 == null || lotNoByProdStep9.isEmpty())) {
                    return ResponseInfo.error("该指令还没针车派工采集");
                }
                String lotNo = pcOrderHeadMapping.getOrderIdByDisPatch(req.getDispatchNo());
                Map<String, Object> maps = pcOrderHeadMapping.getWorkerNameByDisPatch(req.getDispatchNo());
                req.setWorkName(maps.get("workerName").toString());
                req.setWorkId(maps.get("workerId").toString());
                req.setLotNo(lotNo);
                list = packMaterialMapping.getDipathchNoByProdStep(req, choose);
                req.setProdType((String) maps.get("prodType"));
                Map<String, Object> map = packMaterialMapping.getDipathchNoByProdStepType(req, choose);
                if ("正单".equals(map.get("prodType"))) {
                    prodQty = packMaterialMapping.getProdQtyByStitchNo(req, choose);
                    prodQty = prodQty == null ? new BigDecimal("0") : prodQty;
                    currentQty = packMaterialMapping.getCurrentOrderQty(req);
                    currentQty = currentQty == null ? new BigDecimal("0") : currentQty;
                    req.setReplenishmentQty(prodQty);
                    if (list != null && !list.isEmpty()) {
                        BigDecimal subtract = pcOrderHeadMapping.getProdQtyByLot(req, choose);
                        if (subtract != null || !subtract.equals(new BigDecimal("0")))
                            return ResponseInfo.error("该指令已被采集");
                        subtract = subtract == null ? new BigDecimal("0") : subtract;
                        subtract = subtract.add(prodQty);
                        return getInfo(req, choose, currentQty, prodQty, subtract, prodStep, user);
                    }
                } else if ("补单".equals(map.get("prodType"))) {
                    req.setReplenishmentQty(new BigDecimal(String.valueOf(map.get("prodQty"))));
                }
                packMaterialMapping.insertIntoProdStep(req, prodStep, choose, user);
                return ResponseInfo.ok("采集完成");
            case "11":
                prodStep = "成型投产";
                if ((lotNoByProdStep10 == null || lotNoByProdStep10.isEmpty())) {
                    return ResponseInfo.error("该指令还没针车采集");
                }
                list = packMaterialMapping.getLotNoByProdStep(req, choose);
                if (list != null && !list.isEmpty()) {
                    BigDecimal subtract = currentQty.subtract(prodQty);
                    return getInfo(req, choose, currentQty, prodQty, subtract, prodStep, user);
                }
                packMaterialMapping.insertIntoProdStep(req, prodStep, choose, user);
                return ResponseInfo.ok("采集完成");
            case "12":
                prodStep = "成型完成";
                if ((lotNoByProdStep11 == null || lotNoByProdStep11.isEmpty())) {
                    return ResponseInfo.error("该指令还没成型投产采集");
                }
                list = packMaterialMapping.getLotNoByProdStep(req, choose);
                if (list != null && !list.isEmpty()) {
                    BigDecimal subtract = currentQty.subtract(prodQty);
                    return getInfo(req, choose, currentQty, prodQty, subtract, prodStep, user);
                }
                packMaterialMapping.insertIntoProdStep(req, prodStep, choose, user);
                String scheduleNo = packMaterialMapping.getScheduleNo();
                packMaterialMapping.deleteByPcLotHead(req.getLotNo(), scheduleNo);
                return ResponseInfo.ok("采集完成");
            case "13":
                prodStep = "出货完成";
                if ((lotNoByProdStep12 == null || lotNoByProdStep12.isEmpty())) {
                    return ResponseInfo.error("该指令还没成型完成采集");
                }
                list = packMaterialMapping.getCutStep(req, choose);
                if (list != null && !list.isEmpty()) {
                    BigDecimal subtract = currentQty.subtract(prodQty);
                    return getInfo(req, choose, currentQty, prodQty, subtract, prodStep, user);
                }
                packMaterialMapping.insertIntoProdStep(req, prodStep, choose, user);
                return ResponseInfo.ok("采集完成");
            case "15":
                prodStep = "成型入库";
                if ((lotNoByProdStep13 == null || lotNoByProdStep13.isEmpty())) {
                    return ResponseInfo.error("该指令还没出货完成采集");
                }
                list = packMaterialMapping.getCutStep(req, choose);
                if (list != null && !list.isEmpty()) {
                    BigDecimal subtract = currentQty.subtract(prodQty);
                    return getInfo(req, choose, currentQty, prodQty, subtract, prodStep, user);
                }
                packMaterialMapping.insertIntoProdStep(req, prodStep, choose, user);
                return ResponseInfo.ok("采集完成");

        }
        return ResponseInfo.error("参数有误");
    }

    @NotNull
    private ResponseInfo<Object> getInfo(ScanCollectionAllReq req, String choose, BigDecimal currentQty, BigDecimal prodQty, BigDecimal subtract, String prodStep, SysUserTokenDTO user) {
        if (prodStep.equals("针车完成")) {
            if (!(currentQty.subtract(subtract).doubleValue() <= 0)) {
                req.setReplenishmentQty(prodQty);
                packMaterialMapping.insertIntoProdStep(req, prodStep, choose, user);
                return ResponseInfo.ok("采集完成");
            } else return ResponseInfo.error("该指令已被采集或者采集数大于订单数");
        } else {
            if (!(currentQty.subtract(prodQty).doubleValue() <= 0)) {
                req.setReplenishmentQty(subtract);
                packMaterialMapping.insertIntoProdStep(req, prodStep, choose, user);
                return ResponseInfo.ok("采集完成");
            } else return ResponseInfo.error("该指令已被采集");
        }
    }

    @Override
    public void downloadCollection(HttpServletResponse response, PcOrderDataRsjRequest req) throws IOException {
        Map<String, Object> map = new HashMap<>();
        List<PcDesignGetRep> list = packMaterialMapping.collectAllList(req);
        BigDecimal prodTotal = packMaterialMapping.collectAllProdQty(req);
        map.put("prodTotal", prodTotal);
        String date = new SimpleDateFormat("yyyy/MM/dd").format(new Date());
        map.put("date", date);
        int seq = 1;
        for (PcDesignGetRep pcDesignGetRep : list) {
            pcDesignGetRep.setSeqNo(seq++);
        }
        if (req.getChoose().equals("8")) {
            SimpleDateFormat format = new SimpleDateFormat("MM/dd");
            if (req.getCompleteStartTime() == null || req.getCompleteEndTime() == null) return;
            map.put("startTime", format.format(req.getCompleteStartTime()));
            map.put("endTime", format.format(req.getCompleteEndTime()));
            ExcelUtils.creatByTemplate(response, "裁剪配套日报表模板.xls", "裁剪配套日报表_" + DateUtils.dateTimeNow(), list, map);
        } else if (req.getChoose().equals("9")) {
            ExcelUtils.creatByTemplate(response, "鞋部针车派工日报表模板.xls", "鞋部针车派工日报表_" + DateUtils.dateTimeNow(), list, map);
        } else if (req.getChoose().equals("10")) {
            ExcelUtils.creatByTemplate(response, "鞋部针车完成日报表模板.xls", "鞋部针车派工日报表_" + DateUtils.dateTimeNow(), list, map);
        } else if (req.getChoose().equals("17")) {
            List<PcCutStitchRep> lists = packMaterialMapping.collectCutD1(req);
            int i = 1;
            for (PcDesignGetRep rep : list) {
                rep.setSeqNo(i++);
            }
            ExcelUtils.creatByTemplate(response, "鞋部针车完成日报表模板.xls", "鞋部针车派工日报表_" + DateUtils.dateTimeNow(), lists, map);
        }
    }

    @Override
    public void downloadCut(HttpServletResponse response, PcOrderDataRsjRequest req) throws IOException {
        Map<String, Object> map = new HashMap<>();
        req.setChoose("16");
        SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");
        String s = format.format(new Date());
        List<PcCutStitchRep> list = packMaterialMapping.collectCutD1(req);
        int seq = 1;
        BigDecimal prodTotal = new BigDecimal("0");
        for (PcCutStitchRep re : list) {
            prodTotal = prodTotal.add(re.getProdQty());
            re.setSeqNo(seq++);
        }
        map.put("date", s);
        map.put("prodTotal", prodTotal);
        ExcelUtils.creatByTemplate(response, "裁断完工日报表模板.xls", "裁断完工日报表_" + DateUtils.dateTimeNow(), list, map);
    }

    @Override
    public ResponseInfo scanInStatusOther(TestBoardsScan req) {
        if ("".equals(req.getLotNo())) return ResponseInfo.error("指令为空");
        if ("".equals(req.getChoose())) return ResponseInfo.error("");
        req.setProdUserName(UserIdThread.get().getUserName());
        req.setProdUser(UserIdThread.get().getLoginName());
        req.setCompanyId(UserIdThread.get().getCompanyId());
        packMaterialMapping.insertIntoStatusOther(req);
        return ResponseInfo.ok("扫描成功");
    }

    @Override
    public ResponseInfo getSolePurPreMtlOther(PcSoleInStockReq req) {
        if ("1".equals(req.getChoose())) {
            Integer count = packMaterialMapping.getCountByPurNo(req);
            if (count <= 0) return ResponseInfo.error("无此指令单和订购单");
        }
        List<PcSoleInPcProdRep> list = packMaterialMapping.getSolePurPreMtlOther(req);
        return ResponseInfo.ok(list);
    }

    @Override
    public ResponseInfo scanSolePurPreMtlOther(List<PcSoleInPcProdRep> list) {
        for (PcSoleInPcProdRep rep : list) {
            rep.setCompanyId(UserIdThread.get().getCompanyId());
            if (rep.getPurType().contains("正单")) rep.setPurType("正单");
            else rep.setPurType("补单");
        }
        packMaterialMapping.insertIntoOrderProd(list, UserIdThread.get().getUserName(), UserIdThread.get().getLoginName());
        return ResponseInfo.ok();
    }

    @Override
    public ResponseInfo updatePcOrderStatus(PcDesignGetRep rep) {
        LocalDate now = LocalDate.now();
        Date date = rep.getProdDate();
        Instant instant = date.toInstant();
        ZoneId zoneId = ZoneId.systemDefault();
        LocalDate localDate = instant.atZone(zoneId).toLocalDate();
        long between = ChronoUnit.DAYS.between(localDate, now);
        if (between > 3) {
            return ResponseInfo.error("不能超过3天");
        }
        if (new BigDecimal(rep.getOrderQty()).compareTo(new BigDecimal(rep.getProdQty())) < 0) {
            throw new ServiceErrorException("不能大于订单数量");
        }
        packMaterialMapping.updatePcOrderStatus(rep);
        return ResponseInfo.ok("修改成功");
    }
}
